package com.authorize.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.authorize.common.core.controller.BaseController;
import com.authorize.common.core.domain.AjaxResult;
import com.authorize.common.core.domain.entity.SysUser;
import com.authorize.common.core.page.TableDataInfo;
import com.authorize.common.exception.TClientException;
import com.authorize.common.utils.PayUtils;
import com.authorize.common.utils.SecurityUtils;
import com.authorize.system.domain.*;
import com.authorize.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system/authCenter")
public class AuthCenterController  extends BaseController {

    @Autowired
    private IAEntryService aEntryService;

    @Autowired
    private IAGoodService aGoodService;

    @Autowired
    private IAPayConfigService aPayConfigService;

    @Autowired
    private IAOrderService aOrderService;

    @Autowired
    private IAAuthService aAuthService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 获取启用项目列表
     */
    @PostMapping("/entryList")
    public TableDataInfo entryList(){
        AEntry aEntry = new AEntry();
        List<AEntry> list = aEntryService.selectAEntryList(aEntry);
        return getDataTable(list);
    }

    /**
     * 获取启用项目列表
     */
    @PostMapping("/goodList")
    public TableDataInfo goodList(AGood aGood){
        aGood.setStatus(1);
        List<AGood> list = aGoodService.selectAGoodList(aGood);
        return getDataTable(list);
    }

    /**
     * 获取启用支付列表
     */
    @PostMapping("/payList")
    public TableDataInfo payList(){
        APayConfig aPayConfig = new APayConfig();
        aPayConfig.setStatus(1);
        List<APayConfig> list = aPayConfigService.selectAPayConfigList(aPayConfig);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setAppId("");
            list.get(i).setSginKey("");
        }
        return getDataTable(list);
    }

    /**
     * 获取启用项目列表
     */
    @PostMapping("/pay")
    public String pay(PayData payData) throws TClientException {
        //查询商品详情
        AGood aGood = aGoodService.selectAGoodById(payData.getGoodId());
        if(aGood == null){
            throw new TClientException("下单失败，授权规格不存在");
        }
        APayConfig aPayConfig = aPayConfigService.selectAPayConfigById(payData.getPayId());
        if(aPayConfig == null){
            throw new TClientException("下单失败，支付配置不存在");
        }
        AOrder aOrder = new AOrder();
        aOrder.setOutTradeNo("AUTH"+System.currentTimeMillis());
        aOrder.setGoodId(payData.getGoodId());
        aOrder.setPayId(payData.getPayId());
        aOrder.setGoodName(aGood.getGoodName());
        aOrder.setPayMethod(payData.getPayType());
        aOrder.setPrice(aGood.getPrice());
        aOrder.setAuthValue(payData.getAuthValue());
        aOrder.setStatus(1);
        aOrder.setCreateTime(new Date());
        aOrder.setUpdateTime(new Date());
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        aOrder.setCreateBy(sysUser.getUserName());
        //保存订单
        int rows = aOrderService.insertAOrder(aOrder);
        if(rows == 0){
            throw new TClientException("下单失败，订单生成失败");
        }
        try{
            //查询支付渠道，准备拉起支付
            JSONObject params = new JSONObject();
            params.put("outTradeNo",aOrder.getOutTradeNo());
            params.put("goodName",aOrder.getOutTradeNo());
            params.put("price",String.valueOf(aOrder.getPrice()));
            Map<String,String> headers = new HashMap<>();
            headers.put("appid",aPayConfig.getAppId());
            headers.put("channel",String.valueOf(aOrder.getPayMethod()));
            headers.put("type","1");
            String p = JSONObject.toJSONString(params);
            String sign = PayUtils.getSign(p,aPayConfig.getSginKey());
            headers.put("sign",sign.toLowerCase());
            String payUrl = configService.selectConfigByKey("sys.payUrl");
            //请求支付接口
            String result = PayUtils.doPost(payUrl+"/open/api/pay",p,headers);
            JSONObject data = JSONObject.parseObject(result);
            return payUrl+"/open/api/getQrcode?url="+data.get("data").toString();
        }catch (Exception e){
            e.printStackTrace();
            throw new TClientException("下单失败，拉起支付异常");
        }
    }


    /**
     * 查询订单管理列表
     */
    @GetMapping("/orderList")
    public TableDataInfo orderList(AOrder aOrder)
    {
        startPage();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        aOrder.setCreateBy(sysUser.getUserName());
        List<AOrder> list = aOrderService.selectAOrderList(aOrder);
        return getDataTable(list);
    }

    /**
     * 查询授权管理列表
     */
    @GetMapping("/authList")
    public TableDataInfo authList(AAuth aAuth)
    {
        startPage();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        aAuth.setCreateBy(sysUser.getUserName());
        List<AAuth> list = aAuthService.selectAAuthList(aAuth);
        return getDataTable(list);
    }

    /**
     * 获取授权管理详细信息
     */
    @GetMapping(value = "/getAuthInfo/{id}")
    public AjaxResult getAuthInfo(@PathVariable("id") Long id)
    {
        return success(aAuthService.selectAAuthById(id));
    }


}
